import React from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Button, Radio, Layout, Select, DatePicker, Table, Divider, Tag } from 'antd';
import ReactEcharts from 'echarts-for-react';
import Gmap from '@/utils/HshMap/Gmap';
import Glayers from '@/utils/HshMap/Glayers';
import 'ol-ext/control/Legend.css';
import Legend from 'ol-ext/control/Legend';
import VectorSource from 'ol/source/Vector';
import { fromLonLat } from 'ol/proj'
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import LineString from 'ol/geom/LineString';

import Gstyle from '@/utils/HshMap/Gstyle';
import Goverlay from '@/utils/HshMap/Goverlay';

import styles from './index.less'

const { RangePicker } = DatePicker;
const { Option } = Select;
const { Header, Content, Sider } = Layout;
const dateFormat = 'YYYY-MM-DD';
const endDateStr = moment().format(dateFormat);
const startDateStr = moment().month(moment().month() - 3).format(dateFormat);

@connect(({ patrol }) => ({ patrol }))
class PatrolSpecial extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectData: [
        { key: 'station', value: '管理站' },
        { key: 'line', value: '巡护线路' },
        { key: 'person', value: '巡护人员' },
        { key: 'illegal', value: '违法上报' },
      ],
      currentDataSource: [],
      sortedInfo: null,
      currentPage:1,
      pageSize:5,
      selectKey: 'station',
      width: 1366,
      height: 768,
      startDateStr,
      endDateStr,
      map_patrol: 'left_count',
      map_patrol_a_name: '巡护次数分布',
      map_patrol_b_name: '漏巡次数分布',
      legend: null,
      isShowHeatMap: false,
      heatMapCountMin: 100000000,
      heatMapCountMax: 0,
    };
    this.gmap = {};
    this.layer_station = {};
    this.layer_line = {};
    this.layer_heat = {};
    this.map_overlay = null;
    this.featureSelected = null;
    this.pop_container = null;
    this.pop_content = null;
    this.handleResize = this.handleResize.bind(this);
    this.handleMapChange = this.handleMapChange.bind(this);
    this.handlerMouseHover = this.handlerMouseHover.bind(this);
    this.handlerTipClose = this.handlerTipClose.bind(this);
    this.showPatrolStationCountOnMap = this.showPatrolStationCountOnMap.bind(this);
    this.showPatrolLineCountOnMap = this.showPatrolLineCountOnMap.bind(this);
    this.showPatrolPersonCountOnMap = this.showPatrolPersonCountOnMap.bind(this);
    this.showPatrolWorkflowExtOnMap = this.showPatrolWorkflowExtOnMap.bind(this);
  }

  getLegendDatas = (datas) => {
    var data = [];
    for (var item of datas) {
      data.push(item.name);
    }
    return data;
  }

  getSeries = (datas) => {
    var series = [];
    for (var item of datas) {
      series.push({
          name: item.name,
          type: 'bar',
          barCategoryGap: '25%',
          itemStyle: {
            normal: {
              color: item.color,
              label: {
                show: false,		//开启显示
                position: 'top',	//在上方显示
                textStyle: {	    //数值样式
                  color: 'black',
                  fontSize: 12
                }
              }
            }
          },
          dataField: item.dataName,
        }
      );
    }
    return series;
  }

  getEcharOptions = (selectKey) => {
    const datas =  {
      station:[{name:"巡护次数",dataName:"station_patrolNumbers",color:"#FD494B"},{name:"漏巡次数",dataName:"station_noPatrolNumbers",color:"#4BAF75"}],
      line:[{name:"巡护次数",dataName:"line_patrolLineNumbers",color:"#FD494B"},{name:"管理站漏巡次数",dataName:"line_noPatrolStationNumbers",color:"#4BAF75"},{name:"上报事件数量",dataName:"line_reportNumbers",color:"#FFC434"}],
      person:[{name:"巡护样线次数",dataName:"person_patrolLineNumbers",color:"#FD494B"},{name:"巡护管理站次数",dataName:"person_patrolStationNumbers",color:"#4BAF75"},{name:"上报事件数量",dataName:"person_reportNumbers",color:"#FFC434"}],
    }

    return  {
      grid: {
        left: '2%',
        right: '4%',
        bottom: '12%',
        top:'6%',
        containLabel: true
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: { // 坐标轴指示器，坐标轴触发有效
          type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
        }
      },
      legend: {
        y: 'bottom',
        data: this.getLegendDatas(datas[selectKey]),
        itemWidth: 8,
        itemHeight: 8,
        itemGap: 12,
        textStyle: {
          fontSize: 12,
          color: '#a7a7a7'
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dotted',
            color: '#D4D4D4'
          }
        },
        axisLabel: {
          color: '#545454'
        }
      },
      xAxis: {
        type: 'category',
        axisLine: {
          lineStyle: {
            color: '#bfbfbf'
          }
        },
        axisLabel:{
          // interval: 0
          color: '#545454',
        },
        data: [],
      },
      series: this.getSeries(datas[selectKey]),
    };
  }

  getTableColumns = (selectKey,sortedInfo) => {
    var tableColumns = {
      station: [
      {
        title: '管理站名称',
        dataIndex: 'site_name',
        key: 'site_name',
      },
      {
        title: '巡护人数',
        dataIndex: 'member_cnt',
        key: 'member_cnt',
        sorter: (a, b) => a.member_cnt - b.member_cnt,
        sortOrder : sortedInfo && sortedInfo.columnKey === 'member_cnt' && sortedInfo.order,
      },
      {
        title: '巡护次数',
        dataIndex: 'cnt',
        key: 'cnt',
        sorter: (a, b) => a.cnt - b.cnt,
        sortOrder : sortedInfo && sortedInfo.columnKey === 'cnt' && sortedInfo.order,
      },
      {
        title: '漏巡次数',
        key: 'miss_cnt',
        dataIndex: 'miss_cnt',
        sorter: (a, b) => a.miss_cnt - b.miss_cnt,
        sortOrder : sortedInfo && sortedInfo.columnKey === 'miss_cnt' && sortedInfo.order,
      }
    ],
      line: [
      {
        title: '巡护样线',
        dataIndex: 'workflow_name',
        key: 'workflow_name',
      },
      {
        title: '巡护次数',
        dataIndex: 'workflow_cnt',
        key: 'workflow_cnt',
        sorter: (a, b) => a.workflow_cnt - b.workflow_cnt,
        sortOrder : sortedInfo && sortedInfo.columnKey === 'workflow_cnt' && sortedInfo.order,
      },
      {
        title: '管理站漏巡次数',
        key: 'miss_cnt',
        dataIndex: 'miss_cnt',
        sorter: (a, b) => a.miss_cnt - b.miss_cnt,
        sortOrder : sortedInfo && sortedInfo.columnKey === 'miss_cnt' && sortedInfo.order,
      },
      {
        title: '上报事件数量',
        key: 'ext_cnt',
        dataIndex: 'ext_cnt',
        sorter: (a, b) => a.ext_cnt - b.ext_cnt,
        sortOrder : sortedInfo && sortedInfo.columnKey === 'ext_cnt' && sortedInfo.order,
      },
    ],
      person: [
      {
        title: '巡护人员',
        dataIndex: 'username',
        key: 'username',
      },
      {
        title: '巡护样线次数',
        dataIndex: 'workflow_cnt',
        key: 'workflow_cnt',
        sorter: (a, b) => a.workflow_cnt - b.workflow_cnt,
        sortOrder : sortedInfo && sortedInfo.columnKey === 'workflow_cnt' && sortedInfo.order,
      },
      {
        title: '巡护管理站次数',
        key: 'site_cnt',
        dataIndex: 'site_cnt',
        sorter: (a, b) => a.site_cnt - b.site_cnt,
        sortOrder : sortedInfo && sortedInfo.columnKey === 'site_cnt' && sortedInfo.order,
      },
      {
        title: '上报事件数量',
        key: 'ext_cnt',
        dataIndex: 'ext_cnt',
        sorter: (a, b) => a.ext_cnt - b.ext_cnt,
        sortOrder : sortedInfo && sortedInfo.columnKey === 'ext_cnt' && sortedInfo.order,
      },
    ],
    }
    return tableColumns[selectKey];
  }
  // 统计维度切换
  selectChange = value => {

    let a_name = '巡护次数分布';
    let b_name = '漏巡次数分布';
    let isShowHeatMap = false;
    this.setState({ isShowHeatMap })
    this.handlerTipClose();

    let lineSource = new VectorSource({
      projection: 'EPSG:4326',
      features: []
    });
    this.layer_line.setSource(lineSource);
    switch (value) {
      case 'station':
        a_name = '巡护次数分布';
        b_name = '漏巡次数分布';
        this.setState({ selectKey: value, map_patrol_a_name: a_name, map_patrol_b_name: b_name,currentPage:1, currentDataSource: [],sortedInfo: null}, async () => {
          await this.queryServerCommon(this.showPatrolStationCountOnMap)
        });
        break;
      case 'line':
        a_name = '管理站漏巡分布';
        b_name = '上报事件分布';
        this.setState({ selectKey: value, map_patrol_a_name: a_name, map_patrol_b_name: b_name,currentPage:1, currentDataSource: [],sortedInfo: null}, async () => {
          await this.queryServerCommon(this.showPatrolLineCountOnMap)
        });
        break;
      case 'person':
        a_name = '管理站漏巡分布';
        b_name = '上报事件分布';
        this.setState({ selectKey: value, map_patrol_a_name: a_name, map_patrol_b_name: b_name,currentPage:1,currentDataSource: [],sortedInfo: null }, async () => {
          await this.queryServerCommon(this.showPatrolPersonCountOnMap)
        });
        break;
      case 'illegal':
        isShowHeatMap = true;
        this.setState({ selectKey: value, isShowHeatMap }, async () => {
          await this.queryWorkflowExtInfo({})
        });
        break;
    }
    this.layer_station.setVisible(!isShowHeatMap);
    this.layer_line.setVisible(!isShowHeatMap);
    this.layer_heat.setVisible(isShowHeatMap);
    this.handleResize();
  };
  // 时间范围变化回调
  dataChange = (date, dateString) => {
    const { selectKey } = this.state;
    switch (selectKey) {
      case 'station':
          /* this.setState({
            startDateStr: dateString[0],
            endDateStr: dateString[1],
          }, async () => {
            await this.queryServer()
          }); */
        this.setState({ startDateStr: dateString[0], endDateStr: dateString[1] ,currentPage:1,currentDataSource: [],sortedInfo: null}, async () => {
          await this.queryServerCommon(this.showPatrolStationCountOnMap)
        });
        break;
      case 'line':
        this.setState({ startDateStr: dateString[0], endDateStr: dateString[1],currentPage:1,currentDataSource: [],sortedInfo: null}, async () => {
          await this.queryServerCommon(this.showPatrolLineCountOnMap)
        });
        break;
      case 'person':
        this.setState({ startDateStr: dateString[0], endDateStr: dateString[1],currentPage:1,currentDataSource: [],sortedInfo: null }, async () => {
          await this.queryServerCommon(this.showPatrolPersonCountOnMap)
        });
        break;
      case 'illegal':
        this.setState({ startDateStr: dateString[0], endDateStr: dateString[1] }, async () => {
          await this.queryWorkflowExtInfo({})
        });
        break;
    }
  }
  // 列表行点击事件
  rowClick = (record) => {
    // console.log(record);
    const { selectKey } = this.state;
    if ("station" == selectKey) {
      let position = fromLonLat([Number(record.longitude), Number(record.latitude)], 'EPSG:4326')
      this.gmap.setCenter(position);
      this.hightlightSelectedFeature(record.site_id, position);
    } else if ("line" == selectKey) {
      let params = { workflow_id: record.workflow_id };
      this.queryWorkflowInfo(params);
    } else if ("person" == selectKey) {
      let params = { user_id: record.user_id };
      this.queryPersonInfo(params);
    }
  }
  // 组件初始化
  componentDidMount() {
    // 弹出 tip
    this.pop_container = document.getElementById("popup");
    this.pop_content = document.getElementById("popup-content");
    this.pop_closer = document.getElementById("popup-closer");
    this.init();
    this.gmap = new Gmap();
    this.gmap.initMap('patrolMap');
    // 管理站
    this.layer_station = new Glayers().station;
    this.gmap.map.addLayer(this.layer_station);
    // 巡护线路/巡护人员
    this.layer_line = new Glayers().line;
    this.gmap.map.addLayer(this.layer_line);
    // 热力图
    this.layer_heat = new Glayers().event_heatmap;
    this.gmap.map.addLayer(this.layer_heat);
    this.initLegend();
    // hover pop
    this.map_overlay = Goverlay.getBasicOverlay(this.pop_container);
    this.gmap.map.addOverlay(this.map_overlay);
    // 鼠标hover
    // this.gmap.map.on('pointermove', this.handlerMouseHover);
    // 鼠标点击事件
    this.gmap.map.on('click', this.handlerMouseClick);
    // 窗口resize 监听
    this.handleResize();
    window.addEventListener('resize', this.handleResize);
    const self = this;
    setTimeout(function () {
      // 管理站 巡护次数分布
      self.showPatrolStationCountOnMap('left_count');
    }, 2000);
    this.pop_closer.addEventListener('click', this.handlerTipClose, false);
  };
  // 初始化图列
  initLegend(){
    var canvas = document.getElementById('legend');
    var ctx = canvas.getContext("2d");
    ctx.beginPath();
    //线段的起点坐标为(0,0)
    ctx.moveTo(0, 0);
    //线段的终点坐标为(0,0)
    ctx.lineTo(0,140);
    //设置线条宽度为20px
    ctx.lineWidth = 45;
    //创建一个表示线性颜色渐变的CanvasGradient对象，并设置该对象的作用区域就是线段所在的区域
    var canvasGradient = ctx.createLinearGradient(0, 0, 0, 140);
    canvasGradient.addColorStop(1 / 3, '#f00');
    canvasGradient.addColorStop(2 / 3, '#ff0');
    canvasGradient.addColorStop(3 / 3, '#0f0');
    //将strokeStyle的属性值设为该CanvasGradient对象
    ctx.strokeStyle = canvasGradient;
    //最后，绘制出当前绘制路径的图形效果
    ctx.stroke();
  }
  // 取父div的height
  handleResize = () => {
    const self = this;
    const divWidth = document.body.clientWidth;
    const divHeight = document.body.clientHeight;
    this.setState({ width: divWidth, height: divHeight - 66 });
    setTimeout(function () {
      self.gmap.map.updateSize();
    }, 100);
  };
  handlerTipClose = () => {
    const self = this;
    const { selectKey } = self.state;
    if (this.featureSelected !== null) {
      if (this.featureSelected.getGeometry().getType() == 'Point' && selectKey != 'illegal') {
        this.featureSelected.setStyle(Gstyle.station);
      } else if (this.featureSelected.getGeometry().getType() == 'LineString') {
        this.featureSelected.setStyle(Gstyle.line);
      }
      this.map_overlay.setPosition(undefined);
    }
  };
  // 鼠标点击事件 响应
  handlerMouseClick = e => {
    const self = this;
    const { selectKey } = self.state;
    if (this.featureSelected !== null) {
      if (this.featureSelected.getGeometry().getType() == 'Point' && selectKey != 'illegal') {
        this.featureSelected.setStyle(Gstyle.station);
      } else if (this.featureSelected.getGeometry().getType() == 'LineString') {
        this.featureSelected.setStyle(Gstyle.line);
      }
      this.map_overlay.setPosition(undefined);
    }
    this.gmap.map.forEachFeatureAtPixel(e.pixel, function (f) {
      let coodinate = e.coordinate;
      self.featureSelected = f;
      let properties = f.getProperties();
      if (f.getGeometry().getType() == 'Point' && selectKey != 'illegal') {
        f.setStyle(Gstyle.station_hover);
        if (selectKey == 'station') {
          self.pop_content.innerHTML = "<p style='color: #ff0000;font-weight: bold;'>" + properties.properties.site_name + "</p>"
          + "<p>巡护次数：" + properties.properties.cnt + "</p>"
          + "<p>漏巡次数：" + properties.properties.miss_cnt + "</p>";
        } else if (selectKey == 'line' || selectKey == 'person') {
          self.pop_content.innerHTML = "<p style='color: #ff0000;font-weight: bold;'>" + properties.properties.site_name + "</p>"
          + "<p>漏巡次数：" + properties.properties.miss_cnt + "</p>"
          + "<p>上报事件次数：" + properties.properties.ext_cnt + "</p>";
        }
        self.map_overlay.setPosition(coodinate);
      } else if (f.getGeometry().getType() == 'LineString') {
        f.setStyle(Gstyle.line_hover);
        self.pop_content.innerHTML = "<p style='color: #ff0000;font-weight: bold;'>" + properties.name + "</p>";
        self.map_overlay.setPosition(coodinate);
      }
    });
  };
  // 鼠标hover 响应
  handlerMouseHover = e => {
    if (e.dragging) {
      return;
    }
    const self = this;
    const { selectKey } = self.state;
    if (this.featureSelected !== null) {
      if (this.featureSelected.getGeometry().getType() == 'Point' && selectKey != 'illegal') {
        this.featureSelected.setStyle(Gstyle.station);
      } else if (this.featureSelected.getGeometry().getType() == 'LineString') {
        this.featureSelected.setStyle(Gstyle.line);
      }
      this.map_overlay.setPosition(undefined);
    }
    this.gmap.map.forEachFeatureAtPixel(e.pixel, function (f) {
      let coodinate = e.coordinate;
      self.featureSelected = f;
      let properties = f.getProperties();
      if (f.getGeometry().getType() == 'Point' && selectKey != 'illegal') {
        f.setStyle(Gstyle.station_hover);
        if (selectKey == 'station') {
          self.pop_content.innerHTML = "<p style='color: #ff0000;font-weight: bold;'>" + properties.properties.site_name + "</p>"
          + "<p>巡护次数：" + properties.properties.cnt + "</p>"
          + "<p>漏巡次数：" + properties.properties.miss_cnt + "</p>";
        } else if (selectKey == 'line' || selectKey == 'person') {
          self.pop_content.innerHTML = "<p style='color: #ff0000;font-weight: bold;'>" + properties.properties.site_name + "</p>"
          + "<p>漏巡次数：" + properties.properties.miss_cnt + "</p>"
          + "<p>上报事件次数：" + properties.properties.ext_cnt + "</p>";
        }
        self.map_overlay.setPosition(coodinate);
      } else if (f.getGeometry().getType() == 'LineString') {
        f.setStyle(Gstyle.line_hover);
        self.pop_content.innerHTML = "<p style='color: #ff0000;font-weight: bold;'>" + properties.name + "</p>";
        self.map_overlay.setPosition(coodinate);
      }
    });
  };
  // 地图分布切换
  handleMapChange(e) {
    this.setState({ map_patrol: e.target.value });
    const { selectKey } = this.state;
    // 地图部分对应渲染
    switch (selectKey) {
      case 'station':
        this.showPatrolStationCountOnMap(e.target.value);
        break;
      case 'line':
        this.showPatrolWorkflowInfoCountOnMap(e.target.value);
        break;
      case 'person':
        this.showPatrolPersonInfoCountOnMap(e.target.value);
        break;
      case 'illegal':
        this.showPatrolworkflowExtListOnMap();
        break;
    }
  };
  // 地图加载巡护/漏巡次数分布（管理站）
  showPatrolStationCountOnMap(type) {
    type = type == undefined ? this.state.map_patrol : type;
    let data = this.props.patrol['station'];
    if (this.layer_station.setSource == undefined || data == undefined) {
      return;
    }
    let features = [];
    for (let i = 0; i < data.length; i++) {
      let pt = data[i];
      let geometrypt = new Point(fromLonLat([Number(pt.longitude), Number(pt.latitude)], 'EPSG:4326')); //点的坐标
      let count = 0;
      if (type == 'left_count') {
        count = pt.cnt + "";
      } else if (type == 'right_count') {
        count = pt.miss_cnt + "";
      }
      features.push(new Feature({
        geometry: geometrypt,
        properties: pt,
        count: count,
        id: pt.site_id,
        type: type
      }));
    }
    let stationSource = new VectorSource({
      projection: 'EPSG:4326',
      features: features
    });

    this.layer_station.setSource(stationSource);
  };
  // 地图默认选择第一条线路（巡护线路）
  showPatrolLineCountOnMap(result) {
    if (result != undefined) {
      let lineList = result.data.list;
      if (lineList != undefined && lineList.length > 0) {
        this.rowClick(lineList[0]);
      }
    }
  };
  // 地图加载线路站点统计（巡护线路）
  showPatrolWorkflowInfoCountOnMap(type) {
    let data = this.props.patrol['workflowInfo'];
    if (this.layer_station.setSource == undefined || data == undefined) {
      return;
    }
    let station_features = [];
    let line_pts = [];
    for (let i = 0; i < data.length; i++) {
      let pt = data[i];
      let geometry = fromLonLat([Number(pt.longitude), Number(pt.latitude)], 'EPSG:4326');
      line_pts.push(geometry);
      let geometrypt = new Point(geometry); //点的坐标
      let count = 0;
      if (type == 'left_count') {
        count = pt.miss_cnt + "";
      } else if (type == 'right_count') {
        count = pt.ext_cnt + "";
      }
      // 站点数据
      station_features.push(new Feature({
        geometry: geometrypt,
        properties: pt,
        count: count,
        id: pt.site_id,
        type: type
      }));
    }
    let line_features = [];
    if (line_pts.length > 1) {
      // 线路数据
      let geometryln = new LineString(line_pts);
      line_features.push(new Feature({
        geometry: geometryln,
        id: data[0].workflow_id,
        name: data[0].workflow_name,
        type: type,
      }));
    }

    let lineSource = new VectorSource({
      projection: 'EPSG:4326',
      features: line_features
    });
    this.layer_line.setSource(lineSource);

    let stationSource = new VectorSource({
      projection: 'EPSG:4326',
      features: station_features
    });
    this.layer_station.setSource(stationSource);
  };
  // 地图默认选择第一条线路（巡护人员）
  showPatrolPersonCountOnMap(result) {
    if (result != undefined) {
      let userList = result.data.list;
      if (userList != undefined && userList.length > 0) {
        this.rowClick(userList[0]);
      }
    }
  };
  // 地图加载漏巡次数分布（巡护人员）
  showPatrolPersonInfoCountOnMap(type) {
    let data = this.props.patrol['patrolPersonInfo'];
    if (this.layer_station.setSource == undefined || data == undefined) {
      return;
    }
    let station_features = [];
    let line_pts = [];
    for (let i = 0; i < data.length; i++) {
      let pt = data[i];
      let geometry = fromLonLat([Number(pt.longitude), Number(pt.latitude)], 'EPSG:4326');
      line_pts.push(geometry);
      let geometrypt = new Point(geometry); //点的坐标
      let count = 0;
      if (type == 'left_count') {
        count = pt.miss_cnt + "";
      } else if (type == 'right_count') {
        count = pt.ext_cnt + "";
      }
      // 站点数据
      station_features.push(new Feature({
        geometry: geometrypt,
        properties: pt,
        count: count,
        id: pt.site_id,
        type: type
      }));
    }
    let line_features = [];
    if (line_pts.length > 1) {
      // 线路数据
      let geometryln = new LineString(line_pts);
      line_features.push(new Feature({
        geometry: geometryln,
        id: data[0].workflow_id,
        name: data[0].workflow_name,
        type: type,
      }));
    }

    let lineSource = new VectorSource({
      projection: 'EPSG:4326',
      features: line_features
    });
    this.layer_line.setSource(lineSource);

    let stationSource = new VectorSource({
      projection: 'EPSG:4326',
      features: station_features
    });
    this.layer_station.setSource(stationSource);
  };
  // 地图加载热力图（违法上报）
  showPatrolWorkflowExtOnMap(result) {
    let data = this.props.patrol['workflowExtList'];
    if (this.layer_heat.setSource == undefined || data == undefined) {
      return;
    }
    let station_features = [];
    let min = 100000000;
    let max = 0;
    let total = 0;
    /* for (let i = 0; i < data.length; i++) {
      let pt = data[i];
      let cnt = Number(pt.ext_cnt);
      total += cnt
    } */
    for (let i = 0; i < data.length; i++) {
      let pt = data[i];
      let geometry = fromLonLat([Number(pt.longitude), Number(pt.latitude)], 'EPSG:4326');
      let geometrypt = new Point(geometry); //点的坐标
      let cnt = Number(pt.ext_cnt);
      // 站点数据
      station_features.push(new Feature({
        geometry: geometrypt,
        properties: pt,
        count: cnt,
        id: pt.site_id,
      }));
      min = min > cnt ? cnt : min;
      max = max > cnt ? max : cnt;
    }
    this.setState({ heatMapCountMin: min, heatMapCountMax: max });
    let stationSource = new VectorSource({
      projection: 'EPSG:4326',
      features: station_features,
    });
    this.layer_heat.setSource(stationSource);
  };
  // 高亮显示选中的要素
  hightlightSelectedFeature(site_id,coodinate) {
    const { selectKey } = this.state
    let features = this.layer_station.getSource().getFeatures();
    for (let i = 0; i < features.length; i++) {
      let f = features[i];
      if (f.getProperties().id == site_id) {
        f.setStyle(Gstyle.station_hover);
        this.featureSelected = f;
        let properties = f.getProperties();
        if (f.getGeometry().getType() == 'Point' && selectKey != 'illegal') {
          f.setStyle(Gstyle.station_hover);
          if (selectKey == 'station') {
            this.pop_content.innerHTML = "<p style='color: #ff0000;font-weight: bold;'>" + properties.properties.site_name + "</p>"
            + "<p>巡护次数：" + properties.properties.cnt + "</p>"
            + "<p>漏巡次数：" + properties.properties.miss_cnt + "</p>";
          } else if (selectKey == 'line' || selectKey == 'person') {
            this.pop_content.innerHTML = "<p style='color: #ff0000;font-weight: bold;'>" + properties.properties.site_name + "</p>"
            + "<p>漏巡次数：" + properties.properties.miss_cnt + "</p>"
            + "<p>上报事件次数：" + properties.properties.ext_cnt + "</p>";
          }
          this.map_overlay.setPosition(coodinate);
          break;
        } else if (f.getGeometry().getType() == 'LineString') {
          f.setStyle(Gstyle.line_hover);
          this.pop_content.innerHTML = "<p style='color: #ff0000;font-weight: bold;'>" + properties.name + "</p>";
          this.map_overlay.setPosition(coodinate);
          break;
        }
      } else {
        f.setStyle(Gstyle.station);
      }
    }
  };
  init = () => {
    this.queryServer();
  };
  // ajax请求
  queryServer = () => {
    const { dispatch, patrol } = this.props;
    const { selectKey, startDateStr, endDateStr } = this.state;
    console.log(selectKey, 1)
    dispatch({
      type: 'patrol/' + selectKey,
      payload: {
        startDateStr: startDateStr,
        endDateStr: endDateStr,
      },
    });
  };
  // ajax请求，回调函数
  queryServerCommon = (callback) => {
    const { dispatch } = this.props;
    const { selectKey, startDateStr, endDateStr } = this.state;
    dispatch({
      type: 'patrol/' + selectKey,
      payload: {
        startDateStr: startDateStr,
        endDateStr: endDateStr,
      },
    }).then(response => {
      callback(response);
    });
  };
  // ajax请求 巡护线路
  queryWorkflowInfo = (params) => {
    const { dispatch } = this.props;
    const { map_patrol, startDateStr, endDateStr } = this.state;
    const self = this;
    params.startDateStr = startDateStr;
    params.endDateStr = endDateStr;
    dispatch({
      type: 'patrol/workflowInfo',
      payload: params,
    }).then(response => {
      if (response) {
        self.showPatrolWorkflowInfoCountOnMap(map_patrol);
      }
    });
  };
   // ajax请求 巡护人员
   queryPersonInfo = (params) => {
    const { dispatch } = this.props;
    const { map_patrol, startDateStr, endDateStr } = this.state;
    const self = this;
    params.startDateStr = startDateStr;
    params.endDateStr = endDateStr;
    dispatch({
      type: 'patrol/patrolPersonInfo',
      payload: params,
    }).then(response => {
      if (response) {
        self.showPatrolPersonInfoCountOnMap(map_patrol);
      }
    });
  };
  // ajax请求 违法上报
  queryWorkflowExtInfo = (params) => {
    const { dispatch } = this.props;
    const { map_patrol, startDateStr, endDateStr } = this.state;
    const self = this;
    params.startDateStr = startDateStr;
    params.endDateStr = endDateStr;
    dispatch({
      type: 'patrol/workflowExtList',
      payload: params,
    }).then(response => {
      if (response) {
        self.showPatrolWorkflowExtOnMap(map_patrol);
      }
    });
  };

  handleTableChange = (pagination, filters, sorter, extra) => {
    const { pageSize, current } = pagination;
    const currentDataSource = extra.currentDataSource.slice(pageSize*(current-1), pageSize*current)
    this.setState({
      currentDataSource,
      sortedInfo :sorter,
    })
  }
  tableChangePage = (page) => {
    this.setState({ currentPage: page});
  }
  processEcharData = (currentDataSource) => {
    let echarData = {station_XData:[],
                    station_patrolNumbers: [],
                    station_noPatrolNumbers: [],
                    line_XData: [],
                    line_patrolLineNumbers: [],
                    line_noPatrolStationNumbers: [],
                    line_reportNumbers: [],
                    person_XData: [],
                    person_patrolLineNumbers: [],
                    person_patrolStationNumbers: [],
                    person_reportNumbers: [],}
    if(currentDataSource){
      for (var item of currentDataSource) {
        echarData.station_XData.push(item.site_name);
        echarData.station_patrolNumbers.push(item.cnt);
        echarData.station_noPatrolNumbers.push(item.miss_cnt);
        echarData.line_XData.push(item.workflow_name);
        echarData.line_patrolLineNumbers.push(item.workflow_cnt);
        echarData.line_noPatrolStationNumbers.push(item.miss_cnt);
        echarData.line_reportNumbers.push(item.ext_cnt);
        echarData.person_XData.push(item.username);
        echarData.person_patrolLineNumbers.push(item.workflow_cnt);
        echarData.person_patrolStationNumbers.push(item.site_cnt);
        echarData.person_reportNumbers.push(item.ext_cnt);
      }
    }
    return echarData;

  }

  render() {
    const { map_patrol, selectKey, width,pageSize,currentPage, currentDataSource, isShowHeatMap, heatMapCountMin, heatMapCountMax ,sortedInfo} = this.state;
    const { patrol } = this.props;

    let map_left = (width * 0.4 + (width * 0.6 - 230) / 2);
    let left_div_height = (this.state.height - 150) / 2;
    let selectOptions = this.state.selectData.map(ele => {
      return <Option value={ele.key}>{ele.value}</Option>;
    });
    let _echartsOption = {};
    if (this.state.selectKey != 'illegal') {
      if(patrol[selectKey + '_XData']){
        let echarData = {};
        if(currentDataSource && currentDataSource.length > 0){
          echarData = this.processEcharData(currentDataSource);
        }else{
          echarData = this.processEcharData(patrol[selectKey].slice(currentPage-1, pageSize));
        }
        _echartsOption = this.getEcharOptions(selectKey);
        let start = (currentPage - 1) * pageSize;
        let end = pageSize * currentPage;
        _echartsOption.xAxis.data = echarData[selectKey + '_XData']
        const { series } = _echartsOption;
        series.map(ele => {
          ele.data = echarData[ele.dataField]
        });
      }
    }

    return (
      <Layout>
        <div style={{width: '546px',background: 'rgba(255,255,255,0.9)', padding: '0',borderRight:'1px solid #ddd', position: 'absolute',left: 0,zIndex: 999}}>
          <div style={{background: '#EBF5EF',height: '40px',lineHeight: '40px',paddingLeft: '20px'}}><span
            style={{fontSize: '12px',color:'#40AF59'}}>巡护专题</span></div>
          <div>
            <Header style={{ padding: '0px', margin: '0', minWidth: '546px', background: 'transparent' }}>
              <div style={{ textAlign: 'center', fontSize: '12px', color: '#333' }}>
                统计维度 ：
                <Select
                  style={{ width: 100, marginRight: '20px' }}
                  placeholder="选择统计维度"
                  defaultValue={this.state.selectKey}
                  optionFilterProp="children"
                  onChange={e => this.selectChange(e)}
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {selectOptions}
                </Select>
                选择时间范围：
                <RangePicker style={{ width: 240 }}
                  defaultValue={[moment(this.state.startDateStr, dateFormat), moment(this.state.endDateStr, dateFormat)]}
                  format={dateFormat}
                  onChange={this.dataChange} />
              </div>
            </Header>
          </div>
          <Sider width={546} style={{ width: '40%', background: 'transparent', padding: '0px', display: (this.state.selectKey == 'illegal' ? 'none' : 'block') }}>
            <div style={{ height: left_div_height-55}}>
              <ReactEcharts
                option={_echartsOption}
                notMerge={true}
                lazyUpdate={true}
                style={{ width: '100%', height: left_div_height-55, padding: '0' }}
              />
            </div>
            <div style={{ height: left_div_height, width: 'calc(100% - 10px)', margin: '10px 0', padding: '0 20px' }}>
              <Table
                style={{fontSize: '12px', height: left_div_height}}
                // scroll={{y: left_div_height-50}}
                bordered
                onRow={record => {
                  return {
                    onClick: event => { this.rowClick(record) }, // 点击行
                  };
                }}
                onChange={this.handleTableChange}
                size="middle"
                pagination={{ pageSize: this.state.pageSize,current:this.state.currentPage,onChange: this.tableChangePage,}}
                columns={this.getTableColumns(selectKey,sortedInfo)}
                dataSource={this.props.patrol[selectKey]}
              />
            </div>
          </Sider>
        </div>
        <div id="patrolMap" style={{ width: '100%', background: '#fff', border: 'solid #ddd 1px' }}>
          <div style={{ position: 'absolute', left: map_left, marginTop: '10px', zIndex: 2, textAlign: 'center', display: (this.state.selectKey == 'illegal' ? 'none' : 'block') }}>
            <Radio.Group className={styles['ant-radio-button-custom']} value={map_patrol} onChange={this.handleMapChange}>
              <Radio.Button value="left_count">{this.state.map_patrol_a_name}</Radio.Button>
              <Radio.Button value="right_count">{this.state.map_patrol_b_name}</Radio.Button>
            </Radio.Group>
          </div>
          <div id="popup" className={styles['ol-popup']}>
            <a href="#" id="popup-closer" className={styles['ol-popup-closer']}></a>
            <div id="popup-content"></div>
          </div>
          <div className={styles['ol-legend']} style={{ display: (isShowHeatMap ? 'block' : 'none') }}>
            <canvas id="legend" width="45" height="140"></canvas>
            <div style={{ left: '40px',bottom: '6px', position: 'absolute' }}>{ heatMapCountMax }</div>
            <div style={{ left: '40px',top: '5px', position: 'absolute' }}>{ heatMapCountMin }</div>
          </div>
        </div>
      </Layout>
    );
  }
}

export default PatrolSpecial;
